//
//  Node.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 7/27/11.
//  Copyright 2011 Sinnca Studios. All rights reserved.
//

#include "Node.h"

node::node()
{
	parent = NULL;
	
	noOfChildren = 0;
	draw = true;
}

node::~node()
{
	children.clear();
}


node* node::getParent()
{
	return parent;
}
void node::setParent(node* np)
{
	if (parent != NULL)
	{
		parent->removeChild(this);
	}
	
	parent = np;
}
void node::addChild(node* ch)
{
	if (ch != NULL)
	{
		
		ch->setParent(this);
		children.push_back(ch);
		
		noOfChildren++;
	}
}
void node::removeChild(node* ch)
{
	if (ch != NULL && noOfChildren > 0)
	{
		for (int i = 0; i < noOfChildren; i++)
		{
			if (children[i] == ch)
			{
				children.erase(children.begin() + i);
				break;
			}
		}
	}
}




node* checkNode(lua_State* L, int ind)
{
	void* ud = 0;
	
	// check for table object
	luaL_checktype(L, ind, LUA_TTABLE);
	
	// push the key we're looking for (in this case, it's "__self")
	lua_pushstring(L, "__self");
	// get our table
	lua_gettable(L, ind);
	
	// cast userdata pointer to "Node" type
	ud = dynamic_cast<node*>((node*)lua_touserdata(L, -1));
	luaL_argcheck(L, ud != 0, ind, "Incompatible 'node' type...");
	
	return *((node**)ud);
}

static int addChild(lua_State* L)
{
	int n = lua_gettop(L);
	
	node* par = checkNode(L, 1);
	node* chd;
	
	for (int i = 2; i <= n; i++)
	{
		chd = checkNode(L, i);
		par->addChild(chd);
	}
	
	return 0;
}



static const luaL_Reg nodeFuncs[] = {
	
	{"addChild", addChild},
	{NULL, NULL}
};

void registerNode(lua_State* L)
{
	luaL_register(L, "node", nodeFuncs);
	lua_pushvalue(L,-1);
	lua_setfield(L, -2, "__index"); 
}